<?php
namespace App\Models\AdminModels;
use App\Models\ParentModel;
use App\Components\Tools;
use DB;
/**
 * 后台管理员model
 * @author puppet
 */
class Admin extends ParentModel{
  /**
   * 与模型关联的数据表。
   *
   * @var string
   */
  protected $table = 'pt_admin';

  /**
   * DB::直接操作的数据库表名
   * @var string
   */
  protected $db_table = 'pt_admin';

  /**
   * 主键 默认id。
   *
   * @var string
   */
  protected $primaryKey = 'admin_id';

  /**
   * 指定是否模型应该被戳记时间。
   *
   * @var bool
   */
  public $timestamps = false;

  /**
   * 验证账号
   */
  public function validAdminLogin($username,$password){
    $res = DB::table($this->table)
          ->where('admin_name',$username)
          ->where('password', Tools::passwordEncryption($password))
          ->where('status','>=',1)
          ->first();
	// echo '<pre/>';print_r($res);exit;
    return !empty($res) ? $res : false;
  }

  /**
   * 检查管理员是否已经存在
   */
  public function getAdminData($admin_name,$mobile){
    $sql = "SELECT admin_id FROM {$this->db_table} WHERE `status` >= ?";
    $values = [0];
    if(!empty($mobile)){
      $sql .= " AND (admin_name = ? OR mobile = ?)";
      $values[] = $admin_name;
      $values[] = $mobile;

    }else{
      $sql .= " AND admin_name = ?";
      $values[] = $admin_name;
    }
    $res = DB::select($sql,$values);
    return $res;
  }

  /**
   * 根据admin_id，获取单条用户数据
   */
  public function getData($id){
    $res = DB::table($this->table)
          ->where($this->primaryKey,$id)
          ->where('status','>=',0)
          ->first();
    return !empty($res) ? $res : false;
  }



  /**
   * 所有管理员信息
   */
  public function getAllData(){
    $sql = "SELECT a.admin_id,a.admin_name,a.real_name,a.mobile,a.create_time,a.status,b.role_name FROM {$this->db_table} a LEFT JOIN pt_admin_role b ON (a.role_id = b.admin_role_id) AND a.`status` >=? AND b.`status`>=? WHERE a.`status` >=?;";
    return DB::select($sql,[0,0,0]);
  }

  /**
   * 根据role_id角色编号
   * 获取所有权限名称或者权限url
   */
  public function getUserLimitInfo($role_id,$val = 'limit_name'){
    $result = [];
    if($role_id > 0){
      $oAdminRole = new AdminRole;
      $roleinfo = $oAdminRole->db_get(['admin_role_id' =>['=',$role_id],'status'=>['>=',0]]);
      $limits_ids = !empty($roleinfo['limits_ids']) ? (json_decode($roleinfo['limits_ids'],true)) : [];
      !empty($roleinfo) && $result = Tools::getAdminLimitsNameOrUrl($limits_ids,$val);
    }
    return $result;
  }

  /**
   * 翻页展示所有信息
   */
  public function getPageData($params){
    $res = false;
    $limit_num = (isset($params['limit']) && intval($params['limit'])>0 && intval($params['limit']) <= 100) ? $params['limit'] : 10;
    $limit_sta = 0;
    $page = 1;
    if (isset($params['page']) && intval($params['page']) > 0) {
        $limit_sta = intval($limit_num * intval($params['page'] - 1));
        $page = intval($params['page']);
    }
    $cou_sql = "SELECT count(*) as count FROM {$this->db_table} a LEFT JOIN pt_admin_role b ON (a.role_id = b.admin_role_id) AND a.`status` >=? AND b.`status`>=? WHERE a.`status` >=?";
    $sql = "SELECT a.admin_id,a.admin_name,a.real_name,a.mobile,a.create_time,a.status,b.role_name FROM {$this->db_table} a LEFT JOIN pt_admin_role b ON (a.role_id = b.admin_role_id) AND a.`status` >=? AND b.`status`>=? WHERE a.`status` >=?";
    $values = [0,0,0];

    if(isset($params['admin_name']) && !empty($params['admin_name'])){
      $cou_sql .= " AND admin_name like '%{$params['admin_name']}%'";
      $sql .= " AND admin_name like '%{$params['admin_name']}%'";
    }
    if(isset($params['real_name']) && !empty($params['real_name'])){
      $cou_sql .= " AND real_name like '%{$params['real_name']}%'";
      $sql .= " AND real_name like '%{$params['real_name']}%'";
    }
    if(isset($params['mobile']) && !empty($params['mobile'])){
      $cou_sql .= " AND mobile = ?";
      $sql .= " AND mobile = ?";
      $values[] = $params['mobile'];
    }

    $count = DB::select($cou_sql,$values);
    $count = isset($count[0]['count']) ? $count[0]['count'] : 0;
    if(isset($params['order']) && !empty($params['order'])){
        $order_db = ['a.admin_id','',''];
        $sql .= " ORDER BY ";
        foreach ($params['order'] as $order){
            $result = isset($order_db[$order['column']]) ? $order_db[$order['column']] : '';
            !empty($result) && $sql .= $result.' '.$order['dir'].',';
        }
        $sql = substr($sql,0,-1);
    }
    $sql .= " LIMIT $limit_sta,$limit_num";
    $order_list = DB::select($sql, $values);
    $res['data'] = $order_list;
    $res['total'] = $count;
    //总条数记录
    return $res;
  }
  
  /**
   * 获取管理员信息
   */
  public function getAdminServiceData($params){
    $res = false;
    $limit_num = (isset($params['limit']) && intval($params['limit'])>0 && intval($params['limit']) <= 100) ? $params['limit'] : 10;
    $limit_sta = 0;
    $page = 1;
    if (isset($params['page']) && intval($params['page']) > 0) {
      $limit_sta = intval($limit_num * intval($params['page'] - 1));
      $page = intval($params['page']);
    }
    $cou_sql = "SELECT count(*) as count FROM {$this->db_table} a LEFT JOIN pt_admin_role b"
             . " ON (a.role_id = b.admin_role_id) WHERE a.`status` >= ? AND b.`status`>= ? AND a.role_id > ?";
    $sql = "SELECT a.admin_id,a.admin_name,a.real_name,a.type,a.mobile,a.create_time,a.status,b.role_name FROM {$this->db_table} a LEFT JOIN pt_admin_role b"
         . " ON (a.role_id = b.admin_role_id) WHERE a.`status` >= ? AND b.`status`>= ? AND a.role_id > ?";
    $values = [1,1,1];
    $count = DB::select($cou_sql,$values);
    $count = isset($count[0]['count']) ? $count[0]['count'] : 0;
    if(isset($params['order']) && !empty($params['order'])){
      $order_db = ['a.admin_id'];
      $sql .= " ORDER BY ";
      foreach ($params['order'] as $order){
        $result = isset($order_db[$order['column']]) ? $order_db[$order['column']] : '';
        !empty($result) && $sql .= $result.' '.$order['dir'].',';
      }
      $sql = substr($sql,0,-1);
    }
    $sql .= " LIMIT $limit_sta,$limit_num";
    $data_list = DB::select($sql,$values);
    if(!empty($data_list)){
      foreach ($data_list as $key => $val){
        $val['count'] = DB::table('pt_admin_service')->where('admin_id',$val['admin_id'])->where('type',$val['type'])->count();
        $data_list[$key] = $val;
      }
    }
    $res['data'] = $data_list;
    $res['total'] = $count;
    //总条数记录
    return $res;
  }

  /**
   * 获取客服绩效统计信息
   */

  public function getAdminServicePerformance($params){
    $res = false;
    if($params['search_month'] && !empty($params['search_month'])){
      $firstday = $params['search_month'].'-01';//选择月份的第一天
      $startime = strtotime($firstday);//第一天时间戳
      $endtime = strtotime("$firstday +1 month")-1;//选择月份的最后一天时间戳
      $now_month_first_date = date('Y-m-01');//当前月份的第一天
      if($params['search_month'] >= $now_month_first_date){
        $res['code'] = 1;
        $res['msg'] = '请选择过去的月份';
        return $res;
      }
    }else{
      $res['data'] = array();
      return $res;
    }
    $service_id = '(19,34,43,53,61)';
    $sql = "SELECT admin_id,real_name,mobile FROM {$this->db_table}  WHERE  `admin_id` in ".$service_id;
    $values = [];
    $data_list = DB::select($sql, $values);
    if(!empty($data_list)){
      $oUser = new \App\Models\UserModels\User();
      $oUserRemark = new \App\Models\UserModels\UserRemark();
      $oAdminService = new AdminService();
      $oOrder = new \App\Models\UserModels\Order();
      foreach($data_list as $key => $val){
        //分配用户总数
        $count_users = $oAdminService->getSumUsersByAdminId($val['admin_id']);
        $val['sum_users'] = $count_users['sum_users'];
        $val['vip_num'] = $count_users['vip_num'];
        //管理员用户编号
        $admin_user_id = $oUser->db_get(['mobile'=>['=',$val['mobile']]])['user_id'];
        //客服名字
        $val['name'] = $val['real_name'];
        $total_vip = $oAdminService->joinvipNum($val['admin_id'],$startime,$endtime);//上月开通+续费会员数量
        //新会员
//        $val['newvip_num'] = $total_vip['all_num'] - $total_vip['renewal_num'];
        $val['newvip_num']= $oOrder->getCountUserDistributionOrders($admin_user_id,$startime,$endtime);
        //续费会员
        $val['renewal_num'] = $total_vip['renewal_num'];
        //转介绍量
        $val['medium_num'] = $oAdminService->mediumNum($val['admin_id'],$startime,$endtime);
        //服务用户次数
        $val['service_num'] = $oUserRemark->getCountRemark(0,$admin_user_id,date('Y-m-d H:i:s',$startime),date('Y-m-d H:i:s',$endtime));
        //用户信息收集完整度
        $val['userinfo_ratio'] = $oAdminService->userInfoRatio($val['admin_id'],$startime,$endtime);
        //会员活跃度
        $val['brisk_ratio'] = $oAdminService->briskRatio($val['admin_id'],$startime,$endtime);
        $data_list[$key] = $val;
      }
    }
    $res['data'] = $data_list;
    //总条数记录
    return $res;
  }
  
  /**
   * 获取所有客服/销售类型的管理员
   */
  public function getTypeAdmin($type = 1){
    $sql = "SELECT admin_id,real_name FROM pt_admin WHERE `status` = ? AND type = ?";
    return DB::select($sql,[1,$type]);
  }

  /**
   * 获取销售类型的管理员
   */
  public function getSalerAdmin(){
    $sql = "SELECT admin_id,real_name FROM pt_admin WHERE `status` = ? AND role_id = ? ORDER BY update_time DESC";
    return DB::select($sql,[1,6]);
  }
  
}